//
//  LKImageCorpperPickerManager.m
//  LKImagePickerDemo
//
//  Created by LIUKUN-PC on 16/6/4.
//  Copyright © 2016年 liukun. All rights reserved.
//

#import "LKImageCropPicker.h"
#import "RSKImageCropViewController.h"
#import "LKImagePickerManager.h"
#import "LKOptionSheetViewController.h"

#define SCREEN_WIDTH  [[UIScreen mainScreen] bounds].size.width
#define SCREEN_HEIGHT [[UIScreen mainScreen] bounds].size.height

@interface LKImageCropPicker ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate, RSKImageCropViewControllerDelegate, RSKImageCropViewControllerDataSource>

/** 当前控制器，用于推出图片选择控制器 */
@property (nonatomic, weak) UIViewController *currentViewController;

/** 完成回调 */
@property (nonatomic, copy) void(^completionBlock)(UIImage *croppedImage);

@property (nonatomic, assign) LKImageCropPickerSourceType sourceType;

@property (nonatomic, assign) LKImageCropType cropType;

@end

@implementation LKImageCropPicker

#pragma mark - API

- (void)pickCroppedImageWithSourceType:(LKImageCropPickerSourceType)sourceType cropType:(LKImageCropType)cropType completion:(void (^)(UIImage *))completion {
    self.sourceType = sourceType;
    self.cropType = cropType;
    self.completionBlock = completion;
    
    switch (self.sourceType) {
        case LKImageCropPickerSourceTypeAll: {
            LKOptionSheetViewController *sheetVC =[[LKOptionSheetViewController alloc] initWithOptionsArray:@[@"拍照", @"从手机相册选择"] didSelectOptionHandler:^(NSInteger index) {
                if (index == 0) {
                    [self presentImagePickerViewWithSourceType:UIImagePickerControllerSourceTypeCamera];
                } else {
                    [self presentImagePickerViewWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
                }
            }];
            [self.currentViewController presentViewController:sheetVC animated:NO completion:nil];
            
            
        }
        case LKImageCropPickerSourceTypeCamera: {
            [self presentImagePickerViewWithSourceType:UIImagePickerControllerSourceTypeCamera];
        }
        case LKImageCropPickerSourceTypePhotosLibrary: {
            [self presentImagePickerViewWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        }
    }
}

+ (instancetype)imageCropPickerWithCurrentViewController:(UIViewController *)currentViewController {
    LKImageCropPicker *imageCropPicker = [[LKImageCropPicker alloc] init];
    imageCropPicker.currentViewController = currentViewController;
    imageCropPicker.circleRadius = (MIN(SCREEN_WIDTH, SCREEN_HEIGHT) - 30) / 2;
    imageCropPicker.squareLenght = MIN(SCREEN_WIDTH, SCREEN_HEIGHT) - 30;
    imageCropPicker.rectangleSize = CGSizeMake(SCREEN_WIDTH - 30, SCREEN_HEIGHT - 30);
    return imageCropPicker;
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    RSKImageCropViewController *imageCropVC = [[RSKImageCropViewController alloc] initWithImage:image cropMode:RSKImageCropModeCustom];
    imageCropVC.dataSource = self;
    imageCropVC.delegate = self;
    imageCropVC.applyMaskToCroppedImage = YES;
    imageCropVC.avoidEmptySpaceAroundImage = YES;
    //imageCropVC.rotationEnabled = YES; //旋转
    [imageCropVC.cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [imageCropVC.chooseButton setTitle:@"选取" forState:UIControlStateNormal];
    imageCropVC.moveAndScaleLabel.text = @"移动和缩放";
    [picker pushViewController:imageCropVC animated:YES];
}

#pragma mark - RSKImageCropViewControllerDataSource

- (CGRect)imageCropViewControllerCustomMaskRect:(RSKImageCropViewController *)controller {
    CGRect maskRect;
    CGPoint center = controller.view.center;
    switch (self.cropType) {
        case LKImageCropTypeCircle: {
            maskRect = CGRectMake(center.x - self.circleRadius, center.y - self.circleRadius, self.circleRadius * 2, self.circleRadius * 2);
            break;
        }
        case LKImageCropTypeSquare: {
            maskRect = CGRectMake(center.x - self.squareLenght / 2, center.y - self.squareLenght / 2, self.squareLenght, self.squareLenght);
            break;
        }
        case LKImageCropTypeRectangle: {
            maskRect = CGRectMake(center.x - self.rectangleSize.width / 2, center.y - self.rectangleSize.height / 2, self.rectangleSize.width, self.rectangleSize.height);
            break;
        }
        case LKImageCropTypeCustom: {
            maskRect = [[UIScreen mainScreen] bounds];
            break;
        }
    }
    return maskRect;
}

- (UIBezierPath *)imageCropViewControllerCustomMaskPath:(RSKImageCropViewController *)controller {
    CGRect maskRect = controller.maskRect;
    UIBezierPath *path = nil;
    switch (self.cropType) {
        case LKImageCropTypeCircle: {
            path = [UIBezierPath bezierPathWithRoundedRect:maskRect cornerRadius:self.circleRadius];
            break;
        }
        case LKImageCropTypeSquare:
        case LKImageCropTypeRectangle: {
            path = [UIBezierPath bezierPathWithRect:maskRect];
            break;
        }
        case LKImageCropTypeCustom: {
            path = self.cropPath;
            break;
        }
    }
    [path closePath];
    return path;
}


#pragma mark - RSKImageCropViewControllerDelegate

- (void)imageCropViewController:(RSKImageCropViewController *)controller didCropImage:(UIImage *)croppedImage usingCropRect:(CGRect)cropRect rotationAngle:(CGFloat)rotationAngle{
    [controller.navigationController dismissViewControllerAnimated:YES completion:nil];
    if (self.completionBlock) {
        self.completionBlock(croppedImage);
    }
}

- (void)imageCropViewControllerDidCancelCrop:(RSKImageCropViewController *)controller {
    UIImagePickerController *imagePicker = (UIImagePickerController *)controller.navigationController;
    if (imagePicker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        [imagePicker dismissViewControllerAnimated:YES completion:nil];
    } else {
        [imagePicker popViewControllerAnimated:YES];
    }
}


#pragma mark - Private Method

- (void)presentImagePickerViewWithSourceType:(UIImagePickerControllerSourceType)sourceType {
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    
    if ([UIImagePickerController isSourceTypeAvailable: sourceType]) {
        imagePicker.sourceType = sourceType;
        [self.currentViewController presentViewController:imagePicker animated:YES completion:nil];
    } else {
        switch (sourceType) {
            case UIImagePickerControllerSourceTypeCamera:
                NSLog(@"模拟器中无法打开照相机,请在真机中使用");
                break;
            default:
                NSLog(@"无法打开此类型的图片选择器");
                break;
        }
    }
}

@end
